(function () {
	
	
	
    var app, deps;

    deps = ['treeGrid'];

    app = angular.module('treeGridTest', deps);

    app.controller('treeGridController', function ($scope, $timeout) {
        var tree;

        var myTreeData = getCateTreeData();
        
        $scope.tree_data = myTreeData;//赋值语句
        $scope.my_tree = tree = {};
        $scope.expanding_property = {
            field: "categoryName",
            displayName: "类别名",
            sortable: true,
            filterable: true,
            cellTemplate: "<i>{{row.branch[expandingProperty.field]}}</i>"
        };
        $scope.col_defs = [];
        $scope.my_tree_handler = function (branch) {
            //console.log('you clicked on', branch)
        	
        }
    });
    app.controller('TableRowController', function($scope, $timeout) {
		$scope.tableRow = function(branch) {
			$("#categoryId").val(branch.id);
			$("#attrNameTable").bootstrapTable("load",getDatas(branch.id));
		}
    });
    
}).call(this);


function getCateTreeData() {
	var rawTreeData = '';
    $.ajax({
    	url: "../category/getAllEquipment.action",
    	type: "post",
    	async: false,
    	success: function(data) {
    		rawTreeData = data;
    	},
    	error: function() {
    		toastr.error("获取类别数据出错，请联系管理员");
    	}
    });
    var data = rawTreeData;
    var primaryIdName = 'id';
    var parentIdName = 'parentCategoryId';
    if (!data || data.length == 0 || !primaryIdName || !parentIdName)
        return [];

    var tree = [],
        rootIds = [],
        item = data[0],
        primaryKey = item[primaryIdName],
        treeObjs = {},
        parentId,
        parent,
        len = data.length,
        i = 0;

    while (i < len) {
        item = data[i++];
        primaryKey = item[primaryIdName];
        treeObjs[primaryKey] = item;
        parentId = item[parentIdName];

        if (parentId != -1) {
            parent = treeObjs[parentId];

            if (parent.children) {
                parent.children.push(item);
            } else {
                parent.children = [item];
            }
        } else {
            rootIds.push(primaryKey);
        }
    }

    for (var i = 0; i < rootIds.length; i++) {
        tree.push(treeObjs[rootIds[i]]);
    };
    return tree;
}






$(function() {
	
	//验证
	validateInit();
	$('#attrNameTable').bootstrapTable({
		data : getDatas('20171214000001'),
		striped : true, 
		cache : false, 
		pagination : true, 
		sortable : false, 
		toolbar : "#attrNameToolbar",
		sidePagination : "client",
		pageNumber : 1,
		pageSize : 10,
		pageList : [ 10, 25, 50, 100 ], 
		search : true, 
		strictSearch : false,
		showColumns : true, 
		clickToSelect : true,
		uniqueId : 'id',
		columns : [ 
		{
			checkbox:true,
		}, {
			field : 'attrName',
			title : '属性名'
		}, {
			field : 'attrDesc',
			title : '属性描述'
		}, {
			field : 'operate',
			title : '操作'
		}],
		onClickRow : function(row, ele, field) {// 单击

		},
		onDblClickRow : function(row) {// 双击显示详情
			showAttrNameDetail(row);
		}
	});
	
	$("#attrNameTable").bootstrapTable("hideColumn","id");
});
//所属类别是否选择了
var isBsSuggestSelected = false;
var isUpdateBsSuggestSelected = true;
function validateInit() {
	$.validator.addMethod("isBsSuggestSelected", function(value, element) { 
        return isBsSuggestSelected;       
	}, "必须选择给定的所属类别"); 
	$.validator.addMethod("isUpdateBsSuggestSelected", function(value, element) { 
		return isUpdateBsSuggestSelected;       
	}, "必须选择给定的所属类别"); 
	
	$("#addAttrNameForm").validate({
		rules : {
			suggestCategoryId : {
				required : true,
				isBsSuggestSelected : true
			},
			attrName:{
				required:true,
				remote : {
					url : "../attrName/CheckattrName.action",
					type : "post",
					data : {
						"attrName" : function() {
							return $("#addattrModal [name='attrName']").val();
						}
					}
				}
			},
			attrDesc: {
				required : true,
				maxlength : 500,
				minlength : 5
			}
		},
		messages : {
			attrName:{
				remote:"此属性已存在"
			}
		},
		success : function(label, element) {// error是lavel标签，element是input标签
			labelReset(element);

			var myTipLabel = '<i class="glyphicon glyphicon-ok form-control-feedback my-tip-i"></i>';
			
			validCssApply(element, myTipLabel, 'has-success');
			
		},
		errorPlacement : function(label, element) {
			labelReset(element);

			var myTipLabel = '<i class="glyphicon glyphicon-remove form-control-feedback my-tip-i"></i>'
							+'<label class="control-label my-tip-label">'
							+	label.text()
							+'</label>';
			element.addClass("error");
			
			validCssApply(element, myTipLabel, 'has-error');
		}
	});
	$("#updateAttrNameForm").validate({
		rules : {
			suggestUpdateCategoryId : {
				required : true,
				isUpdateBsSuggestSelected : true
			},
			attrName:{
				required:true,
				remote : {
					url : "../attrName/updateCheckattrName.action",
					type : "post",
					data : {
						"attrName" : function() {
							return $("#updateAttrForm [name='attrName']").val();
						},
						"id":function() {
							return $("#updateAttrModal [name='id']").val();
						}
					}
				}
			},
			attrDesc: {
				required : true,
				maxlength : 500,
				minlength : 5
			}
		},
		messages : {
			attrName:{
				remote:"此属性已存在"
			}
		},
		success : function(label, element) {// error是lavel标签，element是input标签
			labelReset(element);

			var myTipLabel = '<i class="glyphicon glyphicon-ok form-control-feedback my-tip-i"></i>';
			
			validCssApply(element, myTipLabel, 'has-success');
			
		},
		errorPlacement : function(label, element) {
			labelReset(element);

			var myTipLabel = '<i class="glyphicon glyphicon-remove form-control-feedback my-tip-i"></i>'
							+'<label class="control-label my-tip-label">'
							+	label.text()
							+'</label>';
			element.addClass("error");
			
			validCssApply(element, myTipLabel, 'has-error');
		}
	});
}

function getDatas(categoryId) {
	var result;
	$.ajax({
		url: "../attrName/query.action",
		type: "post",
		async: false,//是为了内层ajax在之后访问
		data: {"categoryId":categoryId, "attrNameStatus":"1"},
		success: function(data) {
			$(data).each(function(){
				//属性名
				this.categoryName = this.category.categoryName;
				//操作赋值
				this.operate='<button class=\'btn btn-primary btn-xs\' onclick=\'updateAttrName(' + this.id + ')\'>修改</button>&nbsp;'
						+	 '<button class=\'btn btn-danger btn-xs\' onclick=\'singleDelete('+ this.id + ')\'>删除</button>';
			});
			result = data;
		},
		error: function() {
			toastr.error("获取角色信息出错，请联系管理员");
		}
	});
	return result;
}

//新增属性名
function addAttrName() {
	formReset("#addAttrNameForm");
	//addAttrNameFormInit();
	$("#addAttrNameForm [name='categoryId']").val($("#categoryId").val());
	$("#addAttrNameModal").modal("show");
}
function addAttrNameFormInit() {
	$.ajax({
		url: "../category/getAllEquipment.action",
		type: "post",
		success: function(data) {
			var array = [];
			array.splice(0, 0,{'id': '-1', 'word': '超顶级'});
			for(var i=0;i<data.length;i++){
			     var temp = {"id":data[i].id, 'word':data[i].categoryName};
			     array.push(temp);
			}
			
			$("#categoryId").bsSuggest("destroy");
			
			var bsSuggestAreaHtml = '<div class="input-group">'
							      +     '<input type="text" placeholder="支持模糊搜索" class="form-control" id="categoryId" name="suggestCategoryId" >'
							      +     '<input type="hidden" name="categoryId" value="-1"/>'
							      +     '<div class="input-group-btn" id="suggestDiv">'
							      +         '<button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown">'
							      +             '<span class="caret"></span>'
							      +         '</button>'
							      +         '<ul class="dropdown-menu dropdown-menu-right my-treetable-hover" role="menu">'
							      +         '</ul>'
							      +     '</div>'
							      +  '</div>';
			$("#bsSuggestArea").html(bsSuggestAreaHtml);
			
			$("#categoryId").bsSuggest({
				indexId: 0, 
				indexKey: 1, //data.value 的第几个数据，作为input输入框的显示内容
				data: {'value': array}
			}).on('onSetSelectValue', function (e, keyword) {  
				isBsSuggestSelected = true;
				$("#addAttrNameForm [name='categoryId']").val(keyword.id);
			}).on('onUnsetSelectValue', function (e) {  
				isBsSuggestSelected = false;
			});  
		},
		error: function() {
			toastr.error("请求所属类别发生错误，请联系管理员")
		}
	});
}

//保存
function addAttrNameSave() {
	if (!$("#addAttrNameForm").valid()) {
		return false;
	}
	var datas = $("#addAttrNameForm").serialize();
	$.ajax({
		url: "../attrName/save.action",
		type: "post",
		data: datas,
		success: function(data) {
			if (data.success == "true") {
				toastr.success("保存成功");
				$("#attrNameTable").bootstrapTable("load",getDatas($("#categoryId").val()));
			}
		},
		error: function() {
			toastr.error("提交到数据库发生错误，请联系管理员");
		}
	});
	$("#addAttrNameModal").modal("hide");
}

//显示详情
function showAttrNameDetail(attrName) {
	var attrNameDetailHtml = '<p style="text-align: center; color: #6294AD;"><b>基本信息</b></p>'
						+	'<p>id：' + attrName.id + '</p>'
						+	'<p>属性名名称：' + attrName.attrName + '</p>'
						+	'<p>属性名描述：<pre style="white-space: pre-wrap !important;word-wrap: break-word !important;">' + attrName.attrDesc + '</pre></p>'
						+	'<p>创建人：' + getUserNameById(attrName.createUserId) + '</p>'
						+	'<p>创建时间：' + getDefaultTime(attrName.createTime) + '</p>'
						
						+'<hr/><p style="text-align: center; color: #6294AD;"><b>所属类别信息</b></p>'
						+	'<p>类别id：' + attrName.categoryId + '</p>'
						+	'<p>类别名：' + attrName.category.categoryName + '</p>'
						+	'<p>类别描述：<pre style="white-space: pre-wrap !important;word-wrap: break-word !important;">' + attrName.category.categoryDesc + '</pre></p>'
						+	'<p>级别：' + attrName.category.categoryLevel + '</p>'
						+	'<p>创建人：' + getUserNameById(attrName.category.createUserId) + '</p>'
						+	'<p>创建时间：' + getDefaultTime(attrName.category.createTime) + '</p>';
							
		
	$("#attrNameDetailShow").html(attrNameDetailHtml);
	$("#attrNameDetailModal").modal("show");
}



//修改
function updateAttrName(id) {
	$("#updateAttrNameForm [name='id']").val(id);
	
	formReset("#updateAttrNameForm");
	
	$.ajax({
		url: "../attrName/query.action",
		type: "post",
		data: {"id":id},
		async: false,
		success: function(datas) {
			var data = datas[0];
			
			//updateAttrNameInit(data.categoryId,data.category.categoryName);
			$("#updateAttrNameForm [name='attrName']").val(data.attrName);
			$("#updateAttrNameForm [name='attrDesc']").text(data.attrDesc);
			$("#uptSaveBtn").attr("disabled", "disabled");
			
			$("#updateAttrNameForm input,textarea").bind('input', function(){
				$("#uptSaveBtn").removeAttr("disabled");
			});
			$("#updateAttrNameModal").modal("show");
		},
		error: function() {
			toastr.error("获取属性信息出错，请联系管理员");
		}
	});
	
}

function updateAttrNameInit(categoryId,categoryName) {
	$.ajax({
		url: "../category/getAllEquipment.action",
		type: "post",
		success: function(data) {
			var array = [];
			array.splice(0, 0,{'id': '-1', 'word': '超顶级'});
			for(var i=0;i<data.length;i++){
			     var temp = {"id":data[i].id, 'word':data[i].categoryName};
			     array.push(temp);
			}
			
			$("#updateCategoryId").bsSuggest("destroy");
			
			var bsSuggestAreaHtml = '<div class="input-group">'
							      +     '<input type="text" placeholder="支持模糊搜索" class="form-control" id="updateCategoryId" name="suggestUpdateCategoryId" >'
							      +     '<input type="hidden" name="categoryId" value="'+categoryId+'"/>'
							      +     '<div class="input-group-btn" id="suggestDiv">'
							      +         '<button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown">'
							      +             '<span class="caret"></span>'
							      +         '</button>'
							      +         '<ul class="dropdown-menu dropdown-menu-right my-treetable-hover" role="menu">'
							      +         '</ul>'
							      +     '</div>'
							      +  '</div>';
			$("#bsSuggestUpdateArea").html(bsSuggestAreaHtml);
			
			$("#updateCategoryId").bsSuggest({
				indexId: 0, 
				indexKey: 1, //data.value 的第几个数据，作为input输入框的显示内容
				data: {'value': array}
			}).on('onSetSelectValue', function (e, keyword) {  
				isUpdateBsSuggestSelected = true;
				$("#uptSaveBtn").removeAttr("disabled");
				$("#updateAttrNameForm [name='categoryId']").val(keyword.id);
			}).on('onUnsetSelectValue', function (e) {  
				isUpdateBsSuggestSelected = false;
			});  
			$("#updateAttrNameForm [name='suggestUpdateCategoryId']").val(categoryName);
		},
		error: function() {
			toastr.error("请求所属类别发生错误，请联系管理员")
		}
	});
}
function updateAttrNameSave() {
	var attrName = $("#updateAttrNameForm").serialize();
	if (!$("#updateAttrNameForm").valid()) {
		return false;
	}
	$.ajax({
		url: "../attrName/update.action",
		type: "post",
		data: attrName,
		success: function(data) {
			if (data.success == "true") {
				toastr.success("更新成功");
				$("#attrNameTable").bootstrapTable("load",getDatas($("#categoryId").val()));
			}
		},
		error: function() {
			toastr.error("提交到数据库发生错误，请联系管理员");
		}
	});
	$("#updateAttrNameModal").modal("hide");
} 

//批量删除
function batchDelete() {
	var selectedRoles = $("#attrNameTable").bootstrapTable('getSelections');
	//console.log(JSON.stringify(selectedRoles)); //Array[Object, Object, ...]
	//return;
	if(selectedRoles.length == 0){
		toastr.error("请勾选你要删除的数据");
		return false;
	}
	var attrNameIds = new Array();
	$(selectedRoles).each(function(index,attrName){
		attrNameIds[index] = attrName.id;
	})

    deleteCore(attrNameIds);
    
}

function singleDelete(id) {
	var attrIds=new Array();
	attrIds[0]=id;
	deleteCore(attrIds);
}

function deleteCore(attrIds) {
	swal({
        title: "您确定要删除所选信息吗",
        text: "删除后将无法恢复，请谨慎操作！",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "删除",
        closeOnConfirm: false
    }, function () {
    	$.ajax({
    		url: "../attrName/batchDelete.action",
    		type: "post",
    		data: {"attrIds":attrIds},
    		success: function(data) {
    			if (data.success == "true") {
    				swal("删除成功", "您已经永久删除了所选信息。", "success");
    				$("#attrNameTable").bootstrapTable("load",getDatas($("#categoryId").val()));
    			} else {
    				swal("删除失败", "后台业务处理发生错误，请联系管理员", "error");
    			}
    		},
    		error: function() {
    			swal("操作失败", "提交到数据库发生错误，请联系管理员。", "error");
    		}
    	});
    });
}